package spec.rolling_list;

import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.List;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import br.ufpe.cin.dsoa.qos.service.registry.impl.Data;
import br.ufpe.cin.dsoa.qos.service.registry.impl.RollingList;

public class RollingListSpec {

	public RollingList list;
	public int capacity = 10;

	@Before
	public void setUp() throws Exception {
		this.list = new RollingList(capacity);
	}

	@After
	public void tearDown() throws Exception {
		this.list = null;
	}

	@Test
	public void testGetCapacity() {
		assertTrue(this.capacity == this.list.capacity());
	}

	@Test
	public void testAdd() {
		assertTrue(list.size() == 0);
		this.list.add(new Data(10, System.currentTimeMillis()));
		this.list.add(new Data(12, System.currentTimeMillis()));
		assertTrue(list.size() == 2);
	}

	@Test
	public void testListCapicity() {
		assertTrue("Should have max " + list.capacity() + " itens",
				list.size() <= list.capacity());
	}

	@Test
	public void testGetList() {
		List<Data> itens = new ArrayList<Data>();
		for (int i = 0; i < 5; i++) {
			itens.add(new Data(i + 10, System.currentTimeMillis()));
		}
		assertTrue(list.size() == 0);
		list.add(itens);
		assertTrue(list.size() == itens.size());
		assertArrayEquals(itens.toArray(), list.getList().toArray());
	}

	@Test
	public void testGetData() {
		double[] data = new double[5];
		for (int i = 0; i < data.length; i++) {
			data[i] = i + 1;
			list.add(new Data(data[i], System.currentTimeMillis()));
		}

		assertArrayEquals(data, list.getData(), 0);
	}

	@Test
	public void testGetDataByWindowSize() {
		double[] data = new double[5];
		for (int i = 0; i < data.length; i++) {
			data[i] = i + 1;
			list.add(new Data(data[i], System.currentTimeMillis()));
		}

		double[] last2data = { data[data.length - 3], data[data.length - 2],
				data[data.length - 1] };
		assertArrayEquals("with size < capacity", last2data, list.getData(3), 0);
		assertArrayEquals("with size = capacity", data, list.getData(10), 0);
		assertArrayEquals("with size > capacity", data, list.getData(10), 0);

	}

	@Test
	public void testGetDataByTimeAgo() {
		double[] data = new double[5];
		double[] data2 = new double[6];
		for (int i = 0; i < data.length; i++) {
			data[i] = i + 1;
			data2[i] = i + 1;
			list.add(new Data(data[i], System.currentTimeMillis()));
		}
		
		try {
			Thread.sleep(10000);
			list.add(new Data(10, System.currentTimeMillis()));
			data2[5] = 10;
		} catch (InterruptedException e) {
		}
		
		assertArrayEquals("inside in interval", data, list.getData((long) 12), 0);
		assertArrayEquals(data2, list.getData((long) 3), 0);
	}
}
